import {UploadOutlined} from '@ant-design/icons';
import {Button, Divider, message, Popconfirm, Upload} from 'antd';
import React, {useState, useRef} from 'react';
import {PageContainer, FooterToolbar} from '@ant-design/pro-layout';
import ProTable, {ProColumns, ActionType} from '@ant-design/pro-table';
import UpdateForm from './components/UpdateForm';
import PreviewModal from './components/PreviewModal';
import {TableListItem} from './data.d';
import {remove, batchRemove, list, update} from './service';
import {AuthConsumer} from '@/utils/authContent'
import {uploadFile} from "@/utils/uploadFileUtil";


/**
 * 更新
 * @param fields
 */
const handleUpdate = async (fields: TableListItem) => {
  const hide = message.loading('正在更新');
  try {
    const data = await update({...fields});
    hide();
    if (data.code === 1) {
      message.success('更新成功，即将刷新');
      return true;
    }
  } catch (error) {
    hide();
    message.error('更新失败,请重试');
    return false;
  }
  message.error('更新失败,请重试');
  return false;
};


/**
 * 删除
 * @param record
 */
const handleRemove = async (record: TableListItem) => {
  const hide = message.loading('正在删除');
  try {
    const data = await remove(record.fileId);
    hide();
    if (data.code === 1) {
      message.success('删除成功，即将刷新');
      return true;
    }
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
  message.error('删除失败，请重试');
  return false;
};

/**
 *  批量删除
 * @param selectedRows
 */
const handleBatchRemove = async (selectedRows: TableListItem[]) => {
  const hide = message.loading('正在批量删除');
  if (!selectedRows) return true;
  try {
    const fileIds = new Array();
    selectedRows.forEach((row: TableListItem) => {
      fileIds.push(row.fileId);
    })
    const data = await batchRemove(fileIds);
    hide();
    if (data.code === 1) {
      message.success('批量删除成功，即将刷新');
      return true;
    }
  } catch (error) {
    hide();
    message.error('批量删除失败，请重试');
    return false;
  }
  message.error('批量删除失败，请重试');
  return false;
};


const FileTableList: React.FC<{}> = () => {
  // 创建Model可见性
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  // 更新Model可见性
  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
  // 设置更新表单值
  const [updateFormValues, setUpdateFormValues] = useState({});
  // 通过actionRef进行表单刷新
  const actionRef = useRef<ActionType>();
  //  选择行数据的状态
  const [selectedRowsState, setSelectedRows] = useState<TableListItem[]>([]);

  // 删除确认按钮
  const onRemoveConfirm = async (record: TableListItem) => {
    await handleRemove(record);
    actionRef.current?.reloadAndRest?.();
  }

  // 表头
  const columns: ProColumns<TableListItem>[] = [
    {
      title: '编号',
      dataIndex: 'fileId',
      valueType: 'textarea',
      hideInForm: true,
      align: "center",
    },
    {
      title: '文件名',
      dataIndex: 'fileName',
      valueType: 'text',
      copyable: true,
      align: "center",
    },
    {
      title: '文件全名',
      dataIndex: 'fileFull',
      valueType: 'text',
      copyable: true,
      align: "center",
    },
    {
      title: '文件附属类型名称',
      dataIndex: 'typeName',
      valueType: 'text',
      align: "center",
    },
    {
      title: '文件附属标签名称',
      dataIndex: 'fileTagName',
      valueType: 'text',
      align: "center",
    },
    {
      title: '文件附属id',
      dataIndex: 'belongId',
      valueType: 'digit',
      hideInSearch: true,
      align: "center",
    },
    {
      title: '文件路径',
      dataIndex: 'filePath',
      valueType: 'text',
      hideInSearch: true,
      ellipsis: true,
      copyable: true,
      align: "center",
    },
    {
      title: 'URL地址',
      dataIndex: 'url',
      valueType: 'text',
      ellipsis: true,
      hideInSearch: true,
      copyable: true,
      align: "center",
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      align: "center",
      render: (_, record) => (
        <>
          <AuthConsumer name={'base:file:list'}>
            <a   onClick={() => {
              handleModalVisible(true);
              setUpdateFormValues(record);
            }}
            >预览</a>

          </AuthConsumer>
          <AuthConsumer name={'base:file:update'}>
            <Divider type="vertical"/>
            <a onClick={() => {
              handleUpdateModalVisible(true);
              setUpdateFormValues(record);
            }}
            >修改</a>
          </AuthConsumer>
          <AuthConsumer name={'base:file:remove'}>
            <Divider type="vertical"/>
            <Popconfirm
              title="确认需要删除"
              okText="确定"
              cancelText="取消"
              onConfirm={() => onRemoveConfirm(record)}
            >
              <a href="#">删除</a>
            </Popconfirm>
          </AuthConsumer>
        </>
      ),
    },
  ];

  return (
    <PageContainer>
      {/* 表格 */}
      <ProTable<TableListItem>
        headerTitle=""
        actionRef={actionRef}
        // scroll={{y: true}}
        rowKey="fileId"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <AuthConsumer name={'base:file:uploadFile'}>
            <Upload {...uploadFile('FILE_A', 'FILE_A_01', actionRef)}>
              <Button type="primary" icon={<UploadOutlined/>}>上传文件</Button>
            </Upload>
          </AuthConsumer>,
        ]}
        // request = {async (params, sorter, filter) => {
        request={async (params) => {
          // console.log(params)
          const data = await list({...params});
          if (data.code === 1) {
            return {
              data: data.data.rows,
              // success请返回true，不然table会停止解析数据，即使有数据
              success: true,
              // 不传会使用 data 的长度，如果是分页一定要传
              total: data.data.total,
            };
          }
          return {
            data: [],
            success: true,
            total: 0,
          }
        }
        }
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => setSelectedRows(selectedRows),
        }}
      />

      {/* 选择数据的状态 */}
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择 <a style={{fontWeight: 600}}>{selectedRowsState.length}</a> 项&nbsp;&nbsp;
            </div>
          }
        >
          <AuthConsumer name={'base:file:batchRemove'}>
            <Button danger type={"primary"}
                    onClick={async () => {
                      await handleBatchRemove(selectedRowsState);
                      setSelectedRows([]);
                      actionRef.current?.reloadAndRest?.();
                    }}
            >
              批量删除
            </Button>
          </AuthConsumer>
        </FooterToolbar>
      )}


      <PreviewModal
        handleModalVisible={handleModalVisible}
        modalVisible={createModalVisible}
        updateFormValues={updateFormValues}
        actionRef={actionRef}
      ></PreviewModal>

      {/* 更新表单 */}
      <UpdateForm
        updateModalVisible={updateModalVisible}
        handleUpdateModalVisible={handleUpdateModalVisible}
        updateFormValues={updateFormValues}
        handleUpdate={handleUpdate}
        actionRef={actionRef}
      ></UpdateForm>

    </PageContainer>
  );
};

export default FileTableList;
